$(function () {
	var form = document.querySelector("form");
	var usernameInput = document.querySelector('input[name="username"]');
	var passwordInput = document.querySelector('input[name="password"]');
	var errorDisplay = document.querySelector(".error");

	form.addEventListener("submit", function (e) {
		e.preventDefault();
		let usernameValue = usernameInput.value;
		let passwordValue = passwordInput.value;
		let isValid = true;

		clearErrors();

		if (!usernameValue) {
			showError("用户名不能为空。");
			isValid = false;
		}

		if (isValid && !passwordValue) {
			showError("密码不能为空。");
		}

		if (isValid) {
			axios("http://localhost:9000/users/login", {
				method: "POST",
				headers: {
					"Content-Type": "application/json",
				},
				data: JSON.stringify({
					username: usernameValue,
					password: passwordValue,
				}),
			}).then(handleResponse);
		}
	});

	function handleResponse({ data }) {
		if (data.code === 1) {
			sessionStorage.setItem("nickname", data.user.nickname);
			sessionStorage.setItem("id", data.user.id);
			sessionStorage.setItem("token", data.token);
			window.location.href = "index.html";
		} else {
			showError(data.message || "未知错误。");
		}
	}

	function clearErrors() {
		errorDisplay.textContent = "";
	}

	// 显示错误信息
	function showError(message) {
		errorDisplay.textContent = message;
		errorDisplay.style.display = "block";
	}
});
